package com.suo.flter;

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter("/*")
public class ManageFilter implements Filter {
    public void init(FilterConfig config) throws ServletException {
    }

    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        String[] urls = {
                "/index.html",
                "/login.html",
                "/regist.html",
                "/Script/",
                "/static/",
                "/sessionServlet",
                "/logoutServlet",
                "/cookieServlet",
                "/loginServlet",
                "/login_success.html",
                "/isExitServlet",
                "/registServlet",
                "/kaptcha.jpg",
                "/regist_success.html"

        };

        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;

        String url = httpServletRequest.getRequestURL().toString();

        for(String s : urls) {
            if(url.contains(s)){
                chain.doFilter(request,response);
                return;
            }
        }

        HttpSession session = httpServletRequest.getSession();

        Object username = session.getAttribute("username");


        if (username != null) {
            chain.doFilter(request,response);
        }
        else {
            httpServletResponse.sendRedirect("http://localhost:8080/library/pages/user/login.html");
        }
    }
}
